import { defineStore } from 'pinia'
import { useLoginApi } from '@/api/login'
import { useBaseRedisApi } from '@/api/base/redis'
import { eachTree, searchTree } from 'xe-utils'
import { i18n } from '@/i18n'
import { token } from '@/storage'
import { Local } from '@/utils/storage'
import sex0 from '@/assets/sex-0.png'
import sex1 from '@/assets/sex-1.png'

// @ts-ignore 不校验 i18n.global 规则冲突 (Vue: Type instantiation is excessively deep and possibly infinite.)
const { t } = i18n.global

const { signUserInfo, signIn } = useLoginApi()
const { GetBaseRedisCache } = useBaseRedisApi()

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
  state: (): UserInfosState => ({
    userInfos: {
      id: '',
      login_name: '',
      avatar: '',
      job: '',
      name: '',
      organization: '',
      role: '',
      dep_id: '',
      org_id: '',
      sex: '0'
    },
    login_name: Local.get('login_name')
  }),
  actions: {
    // 登录
    async setUserSignIn(params: LoginForm) {
      const { data } = await signIn(params)
      Local.set('login_name', params.username)
      this.login_name = params.username
      token.value = data.token
      return data
    },
    // 存储用户信息到浏览器缓存
    async setUserInfos() {
      const { data } = await signUserInfo()
      this.userInfos = data.user
      const business = data.business || []
      eachTree(business, (item) => {
        const list = searchTree(
          item.children,
          (child) => !child.children.length && !child.meta.isHide
        )
        if (item.children?.length && !item.meta.isHide) item.meta.isHide = !list.length
        item.title = t(item.meta.title || '')
      })
      if (!business.some((s) => s.name === 'personal')) {
        business.push({
          path: '/personal',
          name: 'personal',
          component: '/personal/PersonalIndex.vue',
          meta: {
            title: 'message.router.personal',
            isLink: '',
            isHide: false,
            isKeepAlive: true,
            isAffix: false,
            isIframe: false,
            icon: 'iconfont icon-gerenzhongxin'
          }
        })
      }
      await this.setUserInfoAvatar()
      return data
    },
    // 获取头像
    async setUserInfoAvatar() {
      const avatarKey = `${this.userInfos.login_name}_avatar`
      const { data } = await GetBaseRedisCache(avatarKey)
      if (!data) {
        if (this.userInfos.sex === '2') {
          this.userInfos.avatar = sex1
        } else {
          this.userInfos.avatar = sex0
        }
      } else {
        this.userInfos.avatar = data
      }
    }
  }
})
